/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.fee.web;

import com.google.common.collect.Lists;
import com.jeeplus.common.config.Global;
import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.DateUtils;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.common.utils.excel.ExportExcel;
import com.jeeplus.common.utils.excel.ImportExcel;
import com.jeeplus.core.mapper.JsonMapper;
import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.web.BaseController;
import com.jeeplus.modules.fee.entity.Detail;
import com.jeeplus.modules.fee.service.DetailService;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolationException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 计费明细Controller
 * @author weisong
 * @version 2017-09-22
 */
@Controller
@RequestMapping(value = "${adminPath}/fee/detail")
public class DetailController extends BaseController {

	@Autowired
	private DetailService detailService;
	
	@ModelAttribute
	public Detail get(@RequestParam(required=false) String id) {
		Detail entity = null;
		if (StringUtils.isNotBlank(id)){
			entity = detailService.get(id);
		}
		if (entity == null){
			entity = new Detail();
		}
		return entity;
	}
	
	/**
	 * 计费明细列表页面
	 */
	@RequiresPermissions("fee:detail:list")
	@RequestMapping(value = {"list", ""})
	public String list(Detail detail, HttpServletRequest request, HttpServletResponse response, Model model) {
		// 判断引入明细的状态是否为未结算
		String _status = request.getParameter("status");
		if (StringUtils.isNotEmpty(_status)) {
			Integer status = Integer.parseInt(_status);
			detail.setStatus(status);
		}
		//业务属性字段
		String	busyPro = request.getParameter("busyPro");
		if(StringUtils.isNotEmpty(busyPro)){
			detail.setCodes(busyPro);
			model.addAttribute("busyPro",busyPro);
		}
		//设置查询框的起始时间
		if(detail.getStartDate() != null){
			model.addAttribute("startDate",detail.getStartDate());
		}
		//设置查询框的终止时间
		if(detail.getEndDate() != null){
			model.addAttribute("endDate",detail.getEndDate());
		}
		Page<Detail> page = detailService.findPage(new Page<Detail>(request, response), detail);
		//计算汇总
		List<Detail> allDetail = page.getList();
		double sumMoney = 0.00;//初始化汇总金额
		if(null!=allDetail && allDetail.size()>0){
			for(int i=0;i<allDetail.size();i++){
				Detail de = allDetail.get(i);
				if(de.getClearingMoney()!=null && de.getClearingMoney()>0){//优先累加调整金额
					sumMoney += de.getClearingMoney();
				}else{
					sumMoney += de.getPayMoney()!=null?de.getPayMoney():0;
				}
			}
		}
		if(sumMoney >0){
			DecimalFormat df = new DecimalFormat("#.00");
			model.addAttribute("sumMoney",df.format(sumMoney));
		}else{
			model.addAttribute("sumMoney",0.00);
		}
		model.addAttribute("page", page);
		return "modules/fee/detailList";
	}
	
		/**
	 * 计费明细列表数据
	 */
	@ResponseBody
	@RequiresPermissions("fee:detail:list")
	@RequestMapping(value = "data")
	public Map<String, Object> data(Detail detail, HttpServletRequest request, HttpServletResponse response, Model model) {
		Page<Detail> page = detailService.findPage(new Page<Detail>(request, response), detail); 
		return getBootstrapData(page);
	}

	/**
	 * 查看，增加，编辑计费明细表单页面
	 */
	@RequiresPermissions(value={"fee:detail:view","fee:detail:add","fee:detail:edit"},logical=Logical.OR)
	@RequestMapping(value = "form")
	public String form(Detail detail, Model model) {
		model.addAttribute("detail", detail);
		if(StringUtils.isBlank(detail.getId())){//如果ID是空为添加
			model.addAttribute("isAdd", true);
		}
		return "modules/fee/detailForm";
	}

	/**
	 * 保存计费明细
	 */
	@RequiresPermissions(value={"fee:detail:add","fee:detail:edit"},logical=Logical.OR)
	@RequestMapping(value = "save")
	public String save(Detail detail, Model model, RedirectAttributes redirectAttributes) throws Exception{
		if (!beanValidator(model, detail)){
			return form(detail, model);
		}
		//新增或编辑表单保存
		detailService.save(detail);//保存
		addMessage(redirectAttributes, "保存计费明细成功");
		return "redirect:"+Global.getAdminPath()+"/fee/detail/?repage";
	}
	
	/**
	 * 删除计费明细
	 */
	@ResponseBody
	@RequiresPermissions("fee:detail:del")
	@RequestMapping(value = "delete")
	public AjaxJson delete(Detail detail, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		detailService.delete(detail);
		j.setMsg("删除计费明细成功");
		return j;
	}
	
	/**
	 * 批量删除计费明细
	 */
	@ResponseBody
	@RequiresPermissions("fee:detail:del")
	@RequestMapping(value = "deleteAll")
	public AjaxJson deleteAll(String ids, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		String idArray[] =ids.split(",");
		for(String id : idArray){
			detailService.delete(detailService.get(id));
		}
		j.setMsg("删除计费明细成功");
		return j;
	}
	
	/**
	 * 导出excel文件
	 */
	@ResponseBody
	@RequiresPermissions("fee:detail:export")
    @RequestMapping(value = "export", method=RequestMethod.POST)
    public AjaxJson exportFile(Detail detail, HttpServletRequest request, HttpServletResponse response, RedirectAttributes redirectAttributes) {
		AjaxJson j = new AjaxJson();
		try {
            String fileName = "计费明细"+DateUtils.getDate("yyyyMMddHHmmss")+".xlsx";
            Page<Detail> page = detailService.findPage(new Page<Detail>(request, response, -1), detail);
    		new ExportExcel("计费明细", Detail.class).setDataList(page.getList()).write(response, fileName).dispose();
    		j.setSuccess(true);
    		j.setMsg("导出成功！");
    		return j;
		} catch (Exception e) {
			j.setSuccess(false);
			j.setMsg("导出计费明细记录失败！失败信息："+e.getMessage());
		}
			return j;
    }

	/**
	 * 导入Excel数据

	 */
	@RequiresPermissions("fee:detail:import")
    @RequestMapping(value = "import", method=RequestMethod.POST)
    public String importFile(MultipartFile file, RedirectAttributes redirectAttributes) {
		try {
			int successNum = 0;
			int failureNum = 0;
			StringBuilder failureMsg = new StringBuilder();
			ImportExcel ei = new ImportExcel(file, 1, 0);
			List<Detail> list = ei.getDataList(Detail.class);
			for (Detail detail : list){
				try{
					detailService.save(detail);
					successNum++;
				}catch(ConstraintViolationException ex){
					failureNum++;
				}catch (Exception ex) {
					failureNum++;
				}
			}
			if (failureNum>0){
				failureMsg.insert(0, "，失败 "+failureNum+" 条计费明细记录。");
			}
			addMessage(redirectAttributes, "已成功导入 "+successNum+" 条计费明细记录"+failureMsg);
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入计费明细失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/detail/?repage";
    }
	
	/**
	 * 下载导入计费明细数据模板
	 */
	@RequiresPermissions("fee:detail:import")
    @RequestMapping(value = "import/template")
    public String importFileTemplate(HttpServletResponse response, RedirectAttributes redirectAttributes) {
		try {
            String fileName = "计费明细数据导入模板.xlsx";
    		List<Detail> list = Lists.newArrayList(); 
    		new ExportExcel("计费明细数据", Detail.class, 1).setDataList(list).write(response, fileName).dispose();
    		return null;
		} catch (Exception e) {
			addMessage(redirectAttributes, "导入模板下载失败！失败信息："+e.getMessage());
		}
		return "redirect:"+Global.getAdminPath()+"/fee/detail/?repage";
    }

	/**
	 * 计算选中复选框的总金额
	 */
	@RequestMapping(value = "sumPayMoney")
	@ResponseBody
	public String sumPayMoney( HttpServletRequest request){
		String ids = request.getParameter("ids");
		Double payMoney = 0.0;
		if(StringUtils.isNotEmpty(ids)){
			String str[] = ids.split(",");
			if(str.length > 0 || str != null){
				for(String id : str){
					Detail detail = detailService.get(id);
					if(payMoney != 0 ){
						payMoney = payMoney+detail.getPayMoney();
					}else{
						payMoney = detail.getPayMoney();
					}
				}
			}
		}
		return payMoney.toString();
	}

	/**
	 * 跳转到新增应付账款页面
	 */
	@RequestMapping(value = "addPayable")
	public @ResponseBody String addPayable(@RequestParam String ids) {
		// 如果ids为空，则跳转到feeReceivablesForm
		String url = "/fee/detail/?repage";
		List<Detail> list = new ArrayList<Detail>();
		if (StringUtils.isNotEmpty(ids)) { // 判断ids是否为空
			String[] _ids = ids.split(",");
			for (String id : _ids) {
				if (StringUtils.isNotEmpty(id)) {
					Detail feeDetail = detailService.get(id);
					list.add(feeDetail);
				}
			}
		}
		return JsonMapper.toJsonString(list);
	}






}